/*
 Xern Entity Relocation Network
 Copyright (C) 2011 Ronie Salgado <roniesalg@gmail.com>

 This library is free software; you can redistribute it and/or
 modify it under the terms of the GNU Lesser General Public
 License as published by the Free Software Foundation; either
 version 2.1 of the License, or (at your option) any later version.

 This library is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 Lesser General Public License for more details.

 You should have received a copy of the GNU Lesser General Public
 License along with this library; if not, write to the Free Software
 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301
*/

#include "Xern/Exceptions.hpp"
#include "Texture.hpp"
#include "Material.hpp"

namespace XernOgre
{
	Material::Material(Ogre::MaterialPtr material)
		: material(material)
	{
		id = nil_uuid();
	}

	Material::~Material()
	{
	}

	IResource::ResourceFlags Material::GetFlags() const
	{
		return RFL_NONE;
	}

	void Material::UpdateState(boost::shared_ptr<IDataFilter> stateData)
	{
	}

	const uuid &Material::GetId() const
	{
		return this->id;
	}

	void Material::SetId(const uuid &id)
	{
		this->id = id;
	}

	const std::string &Material::GetName() const
	{
		return material->getName();
	}

	bool Material::SetTexture(const std::string &name, boost::shared_ptr<ITexture> texture)
	{
		if(!texture)
			return false;

		boost::shared_ptr<Texture> otex = boost::dynamic_pointer_cast<Texture> (texture);
		if(!otex)
			throw XernException("Expected ogre texture");

		aliases.insert(std::make_pair(name, otex->texture->getName()));
		return true;
	}

	bool Material::SetTexture(const std::string &name, const std::string &textureName)
	{
		aliases.insert(std::make_pair(name, textureName));
		return true;
	}

	const Color &Material::GetAmbient() const
	{
		return ambient;
	}

	void Material::SetAmbient(const Color &c)
	{
		ambient = c;
		material->setAmbient(c.r, c.g, c.b);
	}

	const Color &Material::GetDiffuse() const
	{
		return diffuse;
	}

	void Material::SetDiffuse(const Color &c)
	{
		diffuse = c;
		material->setDiffuse(c.r, c.g, c.b, c.a);
	}

	const Color &Material::GetSpecular() const
	{
		return specular;
	}

	void Material::SetSpecular(const Color &c)
	{
		specular = c;
		material->setSpecular(c.r, c.g, c.b, c.a);
	}

	const Color &Material::GetEmissive() const
	{
		return emissive;
	}

	void Material::SetEmissive(const Color &c)
	{
		emissive = c;
		material->setSelfIllumination(c.r, c.g, c.b);
	}

	bool Material::Prepare()
	{
		if(aliases.empty())
			return true;
		return material->applyTextureAliases(aliases);
	}

}// namespace XernOgre
